import React from "react"
import styles from "./index.module.less"
import { Layout, Tree, Space, Button, Form, Modal } from "antd"
import {
  getTree,
  getObj,
  delDept,
  addDept,
  updateDept,
} from "@/api/admin/dept"
import { TextFormItem, config } from "@/components"

const { Content, Sider } = Layout

export default class DeptContainer extends React.Component {
  componentDidMount() {
    this.getTree()
  }
  getTree() {
    getTree().then((res) => {
      const { data } = res.data
      let treeData = this.getTreeData(data)
      this.setState({ treeData })
    })
  }
  getTreeData(list) {
    let result = []
    if (list.length > 0) {
      list.forEach((i) => {
        let obj = {}
        obj.title = i.name
        obj.key = i.id
        obj.children = this.getTreeData(i.children)
        result.push(obj)
      })
    }
    return result
  }
  state = {
    treeData: [],
    current: {
      name: undefined,
      sort: undefined,
      parentId: undefined,
      deptId: undefined,
    },
    editing: false,
  }
  addNode() {
    const { current } = this.state
    let result = {
      name: undefined,
      sort: undefined,
      deptId: undefined,
    }
    typeof current.deptId !== "undefined"
      ? (result["parentId"] = current.deptId)
      : (result["parentId"] = 0)
    this.setState({ editing: true, current: result })
    this.form.setFieldsValue({ ...result })
  }
  editNode() {
    const { current } = this.state
    this.setState({ editing: typeof current.deptId !== "undefined" })
  }
  delNode() {
    const { current } = this.state
    Modal.confirm({
      title: "提示",
      content: "此操作将永久删除, 是否继续?",
      okText: "确定",
      cancelText: "取消",
      centered: true,
      onOk: () => {
        delDept(current.deptId).then((res) => this.getTree())
      },
      onCancel: () => {
        this.setState({ editing: false })
        this.form.setFieldsValue({
          name: undefined,
          sort: undefined,
          parentId: undefined,
          deptId: undefined,
        })
      },
    })
  }
  onSelect(selectedKeys, e) {
    const { node } = e
    getObj(node.key).then((res) => {
      const { data } = res.data
      this.setState(
        {
          current: {
            name: data.name,
            deptId: data.deptId,
            parentId: data.parentId,
            sort: data.sort,
          },
        },
        () => {
          this.form.setFieldsValue({ ...this.state.current })
        }
      )
    })
  }
  addAndUpdateDept() {
    const { current } = this.state
    const func = current.deptId ? updateDept : addDept
    this.form
      .validateFields()
      .then((values) => {
        values.deptId = current.deptId
        func(values).then((res) => {
          this.getTree()
          this.setState({ editing: false })
          this.form.resetFields()
        })
      })
      .catch((errors) => {
        console.log("-------", errors)
      })
  }
  render() {
    const { treeData, current, editing } = this.state
    const { name, sort, parentId, deptId } = current
    return (
      <Layout className={styles.container}>
        <Sider style={{ backgroundColor: "#fff" }} width={250}>
          <Space style={{ margin: "10px" }}>
            <Button type="primary" onClick={this.addNode.bind(this)}>
              添加
            </Button>
            <Button type="primary" onClick={this.editNode.bind(this)}>
              编辑
            </Button>
            <Button type="primary" onClick={this.delNode.bind(this)}>
              删除
            </Button>
          </Space>
          <Tree treeData={treeData} onSelect={this.onSelect.bind(this)} />
        </Sider>
        <Content>
          <Form
            {...config.getFormLayout()}
            ref={(ref) => {
              this.form = ref
            }}
            initialValues={current}
            style={{
              marginTop: "20px",
              display: "flex",
              flexDirection: "column",
            }}
          >
            <TextFormItem
              label="父级节点"
              value={{ parentId }}
              editing={editing}
            />
            {!editing && (
              <TextFormItem
                label="节点编号"
                value={{ deptId }}
                editing={editing}
              />
            )}
            <TextFormItem label="部门名称" value={{ name }} editing={editing} />
            <TextFormItem label="排序" value={{ sort }} editing={editing} />
            {editing && (
              <Space className={styles.btnGroup}>
                <Button
                  type="primary"
                  onClick={this.addAndUpdateDept.bind(this)}
                >
                  {current.deptId ? "更新" : "保存"}
                </Button>
                <Button onClick={() => this.setState({ editing: false })}>
                  取消
                </Button>
              </Space>
            )}
          </Form>
        </Content>
      </Layout>
    )
  }
}
